package com.naiterui.ehp.bs.wechat.service.impl;

import com.naiterui.ehp.bs.wechat.protocol.msg.subscribe.SubscribeMp;
import com.naiterui.ehp.bs.wechat.protocol.msg.subscribe.SubscribeMsg;
import com.naiterui.ehp.bs.wechat.service.IAccessTokenService;
import com.naiterui.ehp.bs.wechat.service.ISubscribeMsgApiService;
import com.naiterui.ehp.bs.wechat.utils.WeChatApiUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * 订阅通知
 *
 * @author yangfuya
 * @version 1.0
 * @date 2021/4/9 16:02
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class SubscribeMsgApiServiceImpl implements ISubscribeMsgApiService {
    private final IAccessTokenService accessTokenService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer sendSubscribe(String openId, String templateId, String url, SubscribeMp subscribeMp, Map<String, Object> data) {
        return WeChatApiUtil.sendSubscribeMsg(accessTokenService.accessToken(), SubscribeMsg.builder()
                .toUser(openId)
                .templateId(templateId)
                .page(url)
                .miniProgram(subscribeMp)
                .data(createDataMap(data))
                .build());
    }

    private Map<String, SubscribeMsg.Data> createDataMap(Map<String, Object> source) {
        Map<String, SubscribeMsg.Data> dataMap = new HashMap<>();
        source.keySet().forEach(key -> dataMap.put(key, new SubscribeMsg.Data(source.get(key))));
        return dataMap;
    }
}
